﻿using Microsoft.Data.SqlClient;
using System.Threading.Tasks;

namespace DatabaseProxy.DatabaseProxy;

public partial class DatabaseProxyCore
{
    /// <summary>
    /// 数据库连接字符串
    /// </summary>
    public static string? ConnectionString { get; set; }
    /// <summary>
    /// 执行sql
    /// </summary>
    /// <typeparam name="T">返回值类型</typeparam>
    /// <param name="sql">sql</param>
    /// <param name="func">具体执行过程</param>
    /// <param name="parameters">sql中的参数</param>
    /// <returns>sql执行结果</returns>
    private static T ExecuteSql<T>(string sql, Func<SqlCommand, T> func, params SqlParameter[] parameters)
    {
        using SqlConnection connection = new(ConnectionString);
        connection.Open();
        using SqlCommand command = new()
        {
            Connection = connection,
            CommandText = sql,
            CommandType = System.Data.CommandType.Text
        };
        command.Parameters.AddRange(parameters);
        return func(command);
    }
    /// <summary>
    /// 异步执行sql
    /// </summary>
    /// <typeparam name="T">返回值类型</typeparam>
    /// <param name="sql">sql</param>
    /// <param name="func">具体执行过程</param>
    /// <param name="parameters">sql中的参数</param>
    /// <returns>sql执行结果</returns>
    private static async Task<T> ExecuteSqlAsync<T>(string sql, Func<SqlCommand, Task<T>> func, params SqlParameter[] parameters)
    {
        using SqlConnection connection = new(ConnectionString);
        await connection.OpenAsync();
        using SqlCommand sqlCommand = new(sql, connection);
        sqlCommand.Parameters.AddRange(parameters);
        return await func(sqlCommand);
    }
}
